##############################################################################
##############################################################################
##############################################################################
##############################################################################
## Code to install R packages and dependencies used by:
## Zhukov, "Repressed Memories" (JOP)
##############################################################################
##############################################################################
##############################################################################
##############################################################################

# Print upon starting
print("**** Starting run1_setup.R ****")

## Detach non-essential packages
detachAllPackages <- function(){
  basic.packages <- c("package:stats","package:graphics","package:grDevices","package:utils","package:datasets","package:methods","package:base")
  package.list <- search()[ifelse(unlist(gregexpr("package:",search()))==1,TRUE,FALSE)]
  package.list <- setdiff(package.list,basic.packages)
  if (length(package.list)>0)  for (package in package.list) detach(package, character.only=TRUE)
}; detachAllPackages(); rm(detachAllPackages)

## Install and load packages
list.of.packages <- c("BMA","data.table","dplyr","fixest","Formula","lfe","mvtnorm","parallel","rdrobust","sf","splines","spmodel","stringr","SUNGEO","xtable")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]; if(length(new.packages)){install.packages(new.packages,lib=.libPaths()[1],dependencies=TRUE)}
loaded.packages <- lapply(list.of.packages, require, character.only = TRUE)
rm(list.of.packages,new.packages,loaded.packages)

## Turn off s2 processing
suppressMessages({
  sf::sf_use_s2(FALSE)
})

# Disable scientific notation
options(scipen=999)

# Print upon finishing
print("**** Finished run1_setup.R ****")

